package com.qtenv.datasync.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.*;
import com.qtenv.datasync.api.degao.DeGaoApi;
import com.qtenv.datasync.constant.AppConstants;
import com.qtenv.datasync.service.StaticMethodGetBean;
import com.qtenv.datasync.service.entity.convert.DataMeterH;
import com.qtenv.datasync.service.entity.convert.FileFlowMeter;
import com.qtenv.datasync.service.entity.degao.DgTerminalHistory;
import com.qtenv.datasync.service.entity.msmapper.DgTerminalHistoryHMapper;
import com.qtenv.datasync.service.service.IDataMeterHService;
import com.qtenv.datasync.service.service.impl.IDataMeterHServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class CronJob {

    public void run() {
        long start = System.currentTimeMillis();
        IDataMeterHService iDataMeterHService = StaticMethodGetBean.getBean(IDataMeterHService.class);
        System.out.println(iDataMeterHService);

        String startTimePrefix = "T00:00:00";
        String endTimePrefix = "T23:59:59";
        String startDateStr = "2024-04-04";
        String endDateStr = "2024-04-24";
        LocalDate startDate = LocalDate.parse(startDateStr);
        LocalDate endDate = LocalDate.parse(endDateStr);
//        LocalDate startDate = LocalDate.now();
//        LocalDate endDate = LocalDate.now();
        Map<String, List<String>> tenantFfmIDMap = MapUtil.newHashMap();
        try {
            List<FileFlowMeter> terminalList = Db.use().query("select * from dywdma.tbl_file_flow_meter where YL='1'", FileFlowMeter.class);
            Map<String, List<FileFlowMeter>> tenantFfmMap = terminalList.stream().collect(Collectors.groupingBy(item -> item.getTenant_id()));


            while (startDate.isBefore(endDate) || startDate.equals(endDate)) {
//                System.out.println("同步日期：" + startDate);
                String dd = startDate.toString();
                tenantFfmMap.forEach((tenantId, fileFlowMeterList) -> {
                    String tids = String.join(",", fileFlowMeterList.stream().map(item -> item.getFFM_ID().substring(6)).collect(Collectors.toList()));
//                    System.out.println("tenantId===" + tenantId + " and tids===" + tids);
                    String result = DeGaoApi.GetScadaValueByUserTerminals(tids, dd + startTimePrefix, dd + endTimePrefix);
//                System.out.println(result);
                    JSONArray jsonArray = JSONUtil.parseArray(result);
                    List<DataMeterH> dataMeterHList = CollUtil.newArrayList();
                    jsonArray.forEach(json -> {
                        List<Entity> entityList = CollUtil.newArrayList();
                        String userTerminals = JSONUtil.parseObj(json).getStr("Id");
//                        System.out.println("终端地址：" + userTerminals);
                        JSONArray dataArray = JSONUtil.parseObj(json).getJSONArray("Data");
                        dataArray.forEach(da -> {
                            JSONObject daObj = JSONUtil.parseObj(da);
                            DgTerminalHistory dgTerminalHistory = daObj.getJSONObject("Value").toBean(DgTerminalHistory.class);
                            dgTerminalHistory.setUserTerminals(userTerminals);
                            dgTerminalHistory.setReadDate(DateUtil.parse(daObj.getStr("Time"), DatePattern.NORM_DATETIME_FORMAT).toJdkDate());

                            DataMeterH dataMeterH = DgTerminalHistoryHMapper.INSTANCE.toDataMeterH(tenantId, dgTerminalHistory);
                            dataMeterH.setTenant_id(tenantId);
                            dataMeterHList.add(dataMeterH);
                        });

                    });

                    // 去掉重复数据
                    List<DataMeterH> toInsertList = dataMeterHList.stream()
                            .collect(Collectors.collectingAndThen(Collectors.toCollection(
                                    () -> new TreeSet<>(Comparator.comparing(d -> d.getFFM_ID() + "-" + DateUtil.format(d.getFREEZE_DATE(), DatePattern.NORM_DATETIME_FORMAT)))), ArrayList::new));
//                    System.out.println(JSONUtil.toJsonStr(toInsertList, JSONConfig.create().setDateFormat(DatePattern.NORM_DATETIME_PATTERN)));

                    iDataMeterHService.saveToMiddle(toInsertList);
//                    System.out.println("终端数据量：" + toInsertList.size());
//                    System.out.println("本次同步数据耗时：" + (System.currentTimeMillis() - System.currentTimeMillis()) / 1000.0 + "秒");
                });
                startDate = startDate.plusDays(1);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        long end = System.currentTimeMillis();
        System.out.println(DateUtil.now() + " --- 本次同步数据耗时：" + (end - start) / 1000.0 + "秒");
    }

    public static void main(String[] args) {
        CronJob job = new CronJob();
        job.run();
    }
}
